layui.use('table', function () {
    var table = layui.table;
    table.render({
        elem: '#turn_table',
        height: 600,
        url: 'http://' + IPADDRESS + ':' + PORT + '/table/getTableActivityList',  //数据接口
        method: 'post',
        request: {
            pageName: 'page_num',  //页码的参数名称，默认：page
            limitName: 'page_size' //每页数据量的参数名，默认：limit
        },
        parseData: function (res) { //res 即为原始返回的数据
            return {
                "code": res.header.res_code, //解析接口状态
                "msg": res.header.message, //解析提示文本
                "count": res.body.total, //解析数据长度
                "data": res.body.turnTableActivityList //解析数据列表
            };
        },
        response: {
            statusCode: 200000 //规定成功的状态码，默认：0
        },
        page: true,  //开启分页
        cols: [[ //表头
            {field: 'activitykey', title: '活动编号',width:'16%'},
            {field: 'theme', title: '活动主题', toolbar: '#titleTpl',width:'16%'},
            {field: 'people', title: '参与人数', toolbar: '#people_tmp',width:'16%'},
            {field: 'begintime', title: '开始时间',width:'16%'},
            {field: 'endtime', title: '结束时间',width:'16%'},
            {title: '操作', align: 'center', toolbar: '#barDemo'}
        ]],
        limit: 5,
        limits: [5, 10, 20],
        loading: true,
        id: 'tabId'
    });
});

//添加奖项响应
function add_cell(p) {
    layui.use('layer', function () {
        var layer = layui.layer;
        layer.open({
            type: 2,
            content: '../cell-add.html',
            area: [$(window).width() * 0.9 + 'px', $(window).height() - 50 + 'px'],
            fix: false,
            maxmin: true,
            success: function (layero, index) {
                var body = layui.layer.getChildFrame('body', index);
                var activity_key = $(p).parent().parent().parents().eq(0).prevObject[0].innerText.substring(0, 32);
                body.find(".activity_key").val(activity_key);
                layui.form.render();
            }
        });
    });
}

//编辑table
function edit_table(p) {
    layui.use('layer', function () {
        var layer = layui.layer;
        layer.open({
            type: 2,
            content: '../table-edit.html',
            area: [$(window).width() * 0.9 + 'px', $(window).height() - 50 + 'px'],
            fix: false,
            maxmin: true,
            success: function (layero, index) {
                var body = layui.layer.getChildFrame('body', index);
                var activity_key = $(p).parent().parent().parents().eq(0).prevObject[0].innerText.substring(0, 32);

                $.ajax({
                    url: 'http://' + IPADDRESS + ':' + PORT + '/table/getTableById/',
                    type: "POST",
                    contentType: "application/json;charset=utf-8",
                    data: JSON.stringify({'activitykey': activity_key}),
                    dataType: "json",
                    success: function (data) {
                        body.find(".activitykey").val(data.body.activitykey);
                        body.find(".theme").val(data.body.theme);
                        body.find(".share_url").val(data.body.share_url);
                        body.find(".background_url").val(data.body.background_url);
                        body.find(".turntable_url").val(data.body.turntable_url);
                        body.find(".pointer_url").val(data.body.pointer_url);
                        body.find(".begintime").val(data.body.begintime);
                        body.find(".endtime").val(data.body.endtime);
                        body.find(".description").val(data.body.description);
                    }
                })
                layui.form.render();
            }
        });
    });
}

//响应下载按钮
function download(p) {
    var activity_key = $(p).parent().parent().parents().eq(0).prevObject[0].innerText.substring(0, 32);
    var qrcode = new QRCode(document.getElementById("qrcode"), {
        width: 96,
        height: 96
    });
    createQrcode('http://' + IPADDRESS + ':' + PORT8888 + '/index.html?activitykey=' + activity_key);
    layer.open({
        type: 1,
        content: $('#qrcode'),
        btn: ['下载'],
        yes: function (index, layero) {
            downloadQrcode();
            var qrcode = document.getElementById('qrcode');
            qrcode.innerHTML = '';
            layer.close(index);
        },
        end: function () {
            var qrcode = document.getElementById('qrcode');
            qrcode.innerHTML = '';
        },
        resize: false,
        scrollbar: false,
        maxWidth: 300,
        offset: '50px'
    });
}

//创建二维码
function createQrcode(url) {
    qrcode1 = new QRCode(document.getElementById("qrcode"), {
        text: url,
        width: 200, //生成的二维码的宽度
        height: 160, //生成的二维码的高度
        colorDark: "#000000", // 生成的二维码的深色部分
        colorLight: "#ffffff", //生成二维码的浅色部分
        correctLevel: QRCode.CorrectLevel.H
    });
}

//下载
function downloadQrcode() {
    var qrcode = document.getElementById('qrcode');
    var img = qrcode.getElementsByTagName('img')[1];
    var link = document.createElement("a");
    var url = img.getAttribute("src");
    link.setAttribute("href", url);
    link.setAttribute("download", '二维码.png');
    link.click();
}

//奖项设置响应
function open2(activitykey) {

    $('#cell_list').removeClass('layui-hide');

    layer.open({
        type: 1 //Page层类型
        , area: 'auto'
        , title: '奖项设置'
        , area: [$(window).width() * 0.9 + 'px', $(window).height() - 50 + 'px']
        , shade: 0.6 //遮罩透明度
        , maxmin: true //允许全屏最小化
        , anim: 1 //0-6的动画形式，-1不开启
        , content: $('#cell_list')
        , end: function (index, layero) {
            $('#cell_list').addClass('layui-hide');
        }
        , success: function (layero, index) {
            //渲染表格
            layui.use('table', function () {
                var table = layui.table;
                table.render({
                    elem: '#cell_list_table',
                    url: 'http://' + IPADDRESS + ':' + PORT + '/table/getTableCellList/' + activitykey,  //数据接口
                    method: 'post',
                    request: {
                        pageName: 'page_num',  //页码的参数名称，默认：page
                        limitName: 'page_size' //每页数据量的参数名，默认：limit
                    },
                    id: 'listReload',
                    parseData: function (res) { //res 即为原始返回的数据
                        for (var i = 0; i < res.body.length; i++) {
                            if (res.body[i].total == "0" || res.body[i].total === undefined
                                || res.body[i].total == '') {
                                res.body[i].total = '无上限';
                            }

                            if (res.body[i].max_get == "0" || res.body[i].max_get === undefined
                                || res.body[i].max_get == '') {
                                res.body[i].max_get = '无上限';
                            }


                            switch (res.body[i].cell_type) {

                                case "1":
                                    res.body[i].cell_type = "优惠券";
                                    break;
                                case "2":
                                    res.body[i].cell_type = "积分";
                                    break;
                                case "3":
                                    res.body[i].cell_type = res.body[i].goodsname;
                                    res.body[i].quota = "-";
                                    break;
                                case "4":
                                    res.body[i].cell_type = "谢谢惠顾";
                                    res.body[i].quota = "-";
                                    break;
                                default:
                                    console.log("数据出错" + res.body.get(i).cell_type);
                            }
                        }
                        return {
                            "code": res.header.res_code, //解析接口状态
                            "msg": res.header.message, //解析提示文本
                            "count": res.body.total, //解析数据长度
                            "data": res.body //解析数据列表
                        };
                    },

                    response: {
                        statusCode: 200000 //规定成功的状态码，默认：0
                    }
                    ,
                    // page: true,  //开启分页
                    cols: [[ //表头
                        {field: 'prizeorder', title: '奖品序号'},
                        {field: 'cell_type', title: '奖项'},
                        {field: 'quota', title: '面额'},
                        {field: 'total', title: '发行总数'},
                        {field: 'probability', title: '概率权重'},
                        {field: 'max_get', title: '日最大领取次数'},
                        {title: '操作', toolbar: '#cell_delete'}
                    ]],
                    limit:
                        10,
                    loading:
                        true
                });
            });
        }
    });
}

//删除奖项响应
function cell_delete(cellkey) {

    layer.confirm('are you sure?', {icon: 3, title: '注意'}, function (index) {

        $.ajax('http://' + IPADDRESS + ':' + PORT + '/table/deleteCell', {
            method: 'POST',
            contentType: 'application/json; charset=UTF-8',
            dataType: 'json',
            data: JSON.stringify({'cellkey': cellkey})
        }).done(function (data) {
            if (data.header.res_code == '200000') {
                layer.close(index);
                layer.alert(data.header.message, {icon: 1});
                layui.use('table', function () {
                    var table = layui.table;
                    table.reload("listReload", {
                        //此处是上文提到的 初始化标识id
                        // where: {
                        //key: { //该写法上文已经提到
                        // type: item.type, id: item.id
                        //}
                        // }
                    });
                });
            } else {
                layer.alert(data.header.message, {icon: 5});
            }
        })
    });
}

function people_show(activitykey) {

    $('#people_list').removeClass('layui-hide');

    layer.open({
        type: 1 //Page层类型
        , area: 'auto'
        , title: '领取记录'
        , area: [$(window).width() * 0.9 + 'px', $(window).height() - 50 + 'px']
        , shade: 0.6 //遮罩透明度
        , maxmin: true //允许全屏最小化
        , anim: 1 //0-6的动画形式，-1不开启
        , content: $('#people_list')
        , end: function (index, layero) {
            console.log("结束");
            $('#people_list').addClass('layui-hide');
        }
        , success: function (layero, index) {
            console.log("渲染");
            layui.use('table', function () {
                var table = layui.table;
                table.render({
                    elem: '#people_list_table',
                    url: 'http://' + IPADDRESS + ':' + PORT + '/table/getActivityRecord',  //数据接口
                    method: 'post',
                    height: 360,
                    request: {
                        pageName: 'pageNum',  //页码的参数名称，默认：page
                        limitName: 'pageSize'//每页数据量的参数名，默认：limit
                    },
                    parseData: function (res) { //res 即为原始返回的数据
                        for (var i = 0; i < res.body.list.length; i++) {
                            switch (res.body.list[i].prizetype) {
                                case '1':
                                    res.body.list[i].prizetype = res.body.list[i].amount + '元优惠券';
                                    res.body.list[i].total = '1';
                                    break;
                                case '2':
                                    res.body.list[i].prizetype = '积分' + res.body.list[i].pointcount + '个';
                                    res.body.list[i].total = '1';
                                    break;
                                case '3':
                                    res.body.list[i].prizetype = res.body.list[i].goosname;
                                    res.body.list[i].total = '1';
                                    break;
                                case '4':
                                    res.body.list[i].prizetype = '谢谢参与';
                                    res.body.list[i].total = '-';
                                    break;
                                default:
                                    console.log("数据出错啦");
                                    break
                            }
                        }

                        return {
                            "code": res.header.res_code, //解析接口状态
                            "msg": res.header.message, //解析提示文本
                            "count": res.body.total, //解析数据长度
                            "data": res.body.list //解析数据列表
                        };
                    },
                    where: {'activity_key': activitykey},
                    response: {
                        statusCode: 200000 //规定成功的状态码，默认：0
                    },
                    contentType: "application/json;charset=utf-8",
                    page: true,  //开启分页
                    cols: [[ //表头
                        {field: 'prizetype', title: '奖品'},
                        {field: 'total', title: '数量'},
                        {field: 'userkey', title: '用户ID'},
                        {field: 'cardkey', title: '用户卡号'},
                        {field: 'receiveTime', title: '领取时间'}
                    ]],
                    limit: 5,
                    loading: true,

                });
            });
        }
    });
}


function upload_open() {

    //开启弹层
    var upload_index = layer.open({
        type: 1
        , area: 'auto'
        , title: '上传文件'
        , anim: 1
        , offset: ['33%', '300px']
        , content: $('#upload_model')
        , end: function (index, layero) {
            $('#upload_open').addClass('layui-hide');
        }
        , success: function (layero, index) {
            $('#upload_model').removeClass("layui-hide");
        }
    });

    //渲染成上传组件
    var upload_index = layui.use('upload', function () {
        var upload = layui.upload;
        upload.render({
            elem: '#upload',
            title: '请上传一个正常的CSV文件！',
            url: '/table/uploadTurn',
            accept: 'file',
            exts: 'csv',
            field: 'file',
            size: '1024',
            dataType: 'text',
            contenType: 'application/json; charset:UTF-8',
            done: function (res) {
                if (res.header.res_code == '200000') {
                    layui.use('table', function () {
                        var table = layui.table;
                        table.reload("tabId", {});
                    });
                    layer.closeAll();
                    window.location = window.location;
                } else {
                    layer.alert(res.header.message, {icon: 5});
                }
            },
            error: function () {
                windows.location = windows.location;
                console.log("上传异常");
            }
        });
    })
}


